import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import DashView from '../views/DashView.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'dash',
    component: DashView,
    meta: {
      auth: true // 用该字段标记当前路由需要登录
    },
    children: [
      {
        path: '',
        name: 'home',
        component: HomeView,
        meta: {
          auth: true
        },
      },
      {
        path: 'about',
        name: 'about',
        component: () => import('../views/AboutView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'me',
        name: 'me',
        component: () => import('../views/MeView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'forget',
        name: 'forget',
        component: () => import('../views/ForgetPassword.vue')
      },
      {
        path: 'setting',
        name: 'setting',
        component: () => import('../views/SettingView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'activity',
        name: 'activity',
        component: () => import('../views/ActivityView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'activitycategory',
        name: 'activitycategory',
        component: () => import('../views/ActivityCategory.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'role',
        name: 'role',
        component: () => import('../views/RoleView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'admin',
        name: 'admin',
        component: () => import('../views/AdminList.vue'),
        meta: {
          auth: true
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由拦截
router.beforeEach((to, from, next) => {
  // 获取登录凭证
  const token = store.state.userStore.token;
  console.log('每次访问路由都会先调用该函数：', token);

  if (to.meta.auth) { // 表示需要登录才能访问的页面
    if (token) {
      next();
    } else {
      next('/login');
    }
  } else { // 表示访问不需要登录的页面，那么想干嘛干嘛去
    next(); // 只有调用该方法才会进入下一个路由
  }


})

export default router
